import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,ActionSheetController,AlertController,ToastController } from 'ionic-angular';
import {LoginPage} from "../login/login";
import {Camera, CameraOptions} from "@ionic-native/camera";
import {ImagePicker, ImagePickerOptions} from "@ionic-native/image-picker";
import { FileTransfer, FileTransferObject,FileUploadOptions }from'@ionic-native/file-transfer';
import {AppGlobal, AppService} from "../../app/app.service";

/**
 * Generated class for the UserInfoPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-user-info',
  templateUrl: 'user-info.html',
})
export class UserInfoPage {
  user:any;
  loginsts:any;
  pubalterPage:any;

  constructor(public navCtrl: NavController, public navParams: NavParams,
              public actionSheetCtrl: ActionSheetController,public imagePicker: ImagePicker, public camera: Camera,
  public alertCtrl: AlertController,private transfer: FileTransfer,private toastCtrl: ToastController,public appService: AppService) {
    //登录后操作
    this.loginsts = localStorage.getItem('loginsts');
    //电脑测试
    //this.loginsts = "1";
    if (!(this.loginsts == "1")){
      this.navCtrl.push(LoginPage);
    }
    //传过来的用户信息有时得不到值
    // this.user = this.navParams.get("user");

    this.user = JSON.parse(localStorage.getItem('user'));
    this.user = this.user ? JSON.parse(localStorage.getItem('user')) : [];
    console.log(this.user);
    /*电脑测试
    this.user = {
      avatar:'assets/icon/user.jpg',
      nickname:'未名',
      user_id:'未登录',
      companyname:'未名'
    };*/
    this.pubalterPage = 'PubalterPage';
  }

  ionViewDidLoad(){
    console.log("1.0 ionViewDidLoad 当页面加载的时候触发，仅在页面创建的时候触发一次，如果被缓存了，那么下次再打开这个页面则不会触发");
  }
  ionViewWillEnter(){
    console.log("2.0 ionViewWillEnter 顾名思义，当将要进入页面时触发");
    //更新用户信息
    this.user = JSON.parse(localStorage.getItem('user'));
    this.user = this.user ? JSON.parse(localStorage.getItem('user')) : [];
    console.log(this.user);
  }
  ionViewDidEnter(){
    console.log("3.0 ionViewDidEnter 当进入页面时触发");
  }
  ionViewWillLeave(){
    console.log("4.0 ionViewWillLeave 当将要从页面离开时触发");
  }
  ionViewDidLeave(){
    console.log("5.0 ionViewDidLeave 离开页面时触发");
  }

  //修改昵称
  alterNick(){
    console.log(this.user.nickname);
    this.navCtrl.push(this.pubalterPage,{alterparams:this.user.nickname,title:'修改昵称',note:'帅气的昵称提升人气',
      type:'1',user_id:this.user.user_id,sessiontoken:this.user.sessiontoken});
  }
  /*修改公司
  altercompany(){
    this.navCtrl.push(this.pubalterPage,{alterparams:this.user.companyname,title:'公司名称',note:'',type:'2',user_id:this.user.user_id});
  }*/

  presentActionSheet() {
    let actionSheet = this.actionSheetCtrl.create({
      buttons: [{
        text: '拍照',
        role: 'takePhoto',
        handler: () => {
          this.takePhoto();
        }
      }, {
        text: '从相册选择',
        role: 'chooseFromAlbum',
        handler: () => {
          this.chooseFromAlbum();
        }
      }, {
        text: '取消',
        role: 'cancel',
        handler: () => {
          console.log("cancel");
        }
      }]
    });
    actionSheet.present().then(value => {
      return value;
    });
  }
  takePhoto() {
    const options: CameraOptions = {
      quality: 90,
      allowEdit: true,
      targetWidth: 100,
      targetHeight: 100,
      saveToPhotoAlbum: true,
    };
/*
    var cameraOptions = {
      quality: 100,                                            //相片质量0-100
      destinationType: Camera.DestinationType.FILE_URI,        //返回类型：DATA_URL= 0，返回作为 base64 編碼字串。 FILE_URI=1，返回影像档的 URI。NATIVE_URI=2，返回图像本机URI (例如，資產庫)
      sourceType: Camera.PictureSourceType.CAMERA,             //从哪里选择图片：PHOTOLIBRARY=0，相机拍照=1，SAVEDPHOTOALBUM=2。0和1其实都是本地图库
      allowEdit: false,                                        //在选择之前允许修改截图
      encodingType: Camera.EncodingType.JPEG,                   //保存的图片格式： JPEG = 0, PNG = 1
      targetWidth: 200,                                        //照片宽度
      targetHeight: 200,                                       //照片高度
      mediaType: 0,                                             //可选媒体类型：圖片=0，只允许选择图片將返回指定DestinationType的参数。 視頻格式=1，允许选择视频，最终返回 FILE_URI。ALLMEDIA= 2，允许所有媒体类型的选择。
      cameraDirection: 0,                                       //枪后摄像头类型：Back= 0,Front-facing = 1
      popoverOptions: CameraPopoverOptions,
      saveToPhotoAlbum: true
    };
    */

    this.camera.getPicture(options).then(image => {
      console.log('Image URI: ' + image);
      //得到本地图片地址
      this.user.avatar = image.slice(7);
      localStorage.setItem('user',JSON.stringify(this.user));//保存用户信息
      let ops = "." + image.replace(/.+\./, ""); //文件后缀
      let fname = this.user.user_id + ops;
      alert(fname);
      this.upLoadImg({type:1 ,url:image , fname:fname});
      this.user.avatar = image.slice(7);
      //上传成功,修改数据库记录
      let avatar =  AppGlobal.domain+AppGlobal.API.images+"/user/"+fname;
      let user_id = this.user.user_id;
      let sessiontoken = this.user.sessiontoken;
      this.appService.httpPost(AppGlobal.API.updateUser, {user_id:user_id,avatar:avatar,sessiontoken:sessiontoken}, rs => {
        console.debug(rs);
        this.user = rs.data;
        let succ = rs.state;
        if (succ){
          console.debug(succ);
        }
      });
    }, error => {
      console.log('Error: ' + error);
    });
  }

  chooseFromAlbum() {
    const options: ImagePickerOptions = {
      quality: 90,
      maximumImagesCount: 1,
      width: 100,
      height: 100
    };
    this.imagePicker.getPictures(options).then(images => {
      if (images.length > 1) {
        this.presentAlert();
      } else if (images.length === 1) {
        console.log('Image URI: ' + images[0]);
        //得到本地图片地址
        this.user.avatar = images[0].slice(7);
        localStorage.setItem('user',JSON.stringify(this.user));//保存用户信息
        let ops = "." + images[0].replace(/.+\./, ""); //文件后缀
        let fname = this.user.user_id + ops;
        alert(fname);
        this.upLoadImg({type:1 ,url:images[0] , fname:fname});
        this.user.avatar = images[0].slice(7);
        //上传成功,修改数据库记录
        let avatar =  AppGlobal.domain+AppGlobal.API.images+"/user/"+fname;
        let user_id = this.user.user_id;
        let sessiontoken = this.user.sessiontoken;
        this.appService.httpPost(AppGlobal.API.updateUser, {user_id:user_id,avatar:avatar,sessiontoken:sessiontoken}, rs => {
          console.debug(rs);
          this.user = rs.data;
          let succ = rs.state;
          if (succ){
            console.debug(succ);
          }
        });
      }
    }, error => {
      console.log('获取图片失败');
      console.log('Error: ' + error);
    });
  }
  //提示错误
  presentAlert() {
    let alert = this.alertCtrl.create({title: "上传失败", message: "只能选择一张图片作为头像哦", buttons: ["确定"]});
    alert.present().then(value => {
      return value;
    });
  }

  //上传
  upLoadImg(_params:any){
    const fileTransfer: FileTransferObject = this.transfer.create();
    let mime = "";
    let jpgregx = /([^\s]+(?=\.(jpg|jpeg))\.\2)/gi;
    let pngregx = /([^\s]+(?=\.(png))\.\2)/gi;
    if(jpgregx.test(_params.fname)){
      mime = 'image/jpeg';
    }
    else if(pngregx.test(_params.fname)){
      mime = 'image/png';
    }else{
      this.showmsg("只支持jpg|png类型的图片上传");
      return false;
    }
//下面是取token放到header里，可不管
    let tt = this.user.sessiontoken;
    let tokens = "Bearer "+tt;
    let options: FileUploadOptions = {
      fileKey: 'file',
      fileName: _params.fname,
      mimeType: mime,
      headers: {Authorization:tokens}
    };
    alert(_params.url+',-------'+AppGlobal.domain+AppGlobal.API.fileup);
    fileTransfer.upload(_params.url, AppGlobal.domain+AppGlobal.API.fileup, options)
      .then((data) => {
        alert(data.response);
        if(data.response){
          let s = JSON.parse(data.response);
          alert(s.state);
          if(s.state){
            this.user.avatar = _params.url.slice(7);
            this.showmsg("图片上传成功");
          }else{
              this.showmsg(s.message);
          }
        }

      }, (err) => {
        this.showmsg("图片上传时出现异常错误，请稍后再试");
      })
  }

  showmsg(msg, timeout=3000, locate="top"){
    let toast = this.toastCtrl.create({
      message: msg,
      duration: timeout,
      position: locate
    });
    toast.present();
  }
}
